package com.teachoa.web;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.jfinal.plugin.activerecord.Page;
import com.teachoa.bean.User;
import com.teachoa.constant.Global;
import com.teachoa.enumtype.UserTypeEnum;
import com.teachoa.util.IDUtil;
import com.teachoa.util.MD5Util;

public class UserController extends BaseController {
	
	public void index() {
		int pageNo = getParaToInt("pageNo", 1);
		Page<User> userPage = User.dao.findUserByPage(pageNo);
		for(User user:userPage.getList()) {
			user.put("type_display", UserTypeEnum.getEnumByCode(user.getInt("type")).getDesc());
		}
		setAttr("userPage", userPage);
		renderJsp("user.jsp");
	}
	
	public void del() {
		String id = getPara();
		try {
			User.dao.deleteById(id);
			renderJson(success("删除成功！！"));
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(fail("删除失败！！"));
		}
	}
	
	public void save() {
		User user = getModel(User.class);
		String id = user.get("id");
		boolean isAdd = StringUtils.isBlank(id);
		if(isAdd) {
			user.set("id", IDUtil.getId());
			user.set("password", Global.password);
			user.set("create_time", new Date());
		}
		try {
			String msg = "保存成功！！";
			if(isAdd) {
				user.save();
				msg+="初始密码为123456";
			} else {
				user.update();
			}
			renderJson(success(msg));
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(fail("保存失败！！"));
		}
	}
	
	public void load() {
		User user = User.dao.findById(getPara());
		renderJson(JSON.toJSONString(user));
	}
	
	public void pwd() {
		String oldpwd = MD5Util.md5(getPara("oldpwd"));
		String newpwd = MD5Util.md5(getPara("newpwd"));
		User user = getSessionAttr("user");
		if(oldpwd.equals(user.getStr("password"))) {
			user.set("password", newpwd);
			user.update();
			removeSessionAttr("user");
			renderJson(success("密码修改成功！！请重新登陆"));
		} else {
			renderJson(fail("密码输入错误！！"));
		}
	}
	
}
